<template>
  <div class="modal-overlay" @click="$emit('close')">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <div class="header-info">
          <div class="building-icon">{{ building?.icon || '🏢' }}</div>
          <div class="building-title">
            <h2>{{ building?.name }}</h2>
            <div class="building-category">{{ getCategoryName(building?.category) }}</div>
          </div>
        </div>
        <button class="close-btn" @click="$emit('close')">
          ✕
        </button>
      </div>

      <div class="modal-body">
        <!-- 建筑描述 -->
        <div class="info-section">
          <h3>描述</h3>
          <p class="description">{{ building?.description }}</p>
        </div>

        <!-- 建筑效果 -->
        <div class="info-section" v-if="building?.effects?.length">
          <h3>建筑效果</h3>
          <div class="effects-grid">
            <div 
              v-for="effect in building.effects" 
              :key="effect.type"
              class="effect-card"
            >
              <div class="effect-icon">{{ getEffectIcon(effect.type) }}</div>
              <div class="effect-details">
                <div class="effect-name">{{ getEffectName(effect.type) }}</div>
                <div class="effect-value">{{ formatEffectValue(effect) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 建造成本 -->
        <div class="info-section" v-if="building?.cost">
          <h3>建造成本</h3>
          <div class="cost-grid">
            <div 
              v-for="(amount, resource) in building.cost" 
              :key="resource"
              class="cost-card"
              :class="{ insufficient: !hasEnoughResource(resource, amount) }"
            >
              <div class="cost-icon">{{ getResourceIcon(resource) }}</div>
              <div class="cost-details">
                <div class="cost-name">{{ getResourceName(resource) }}</div>
                <div class="cost-amount">{{ formatNumber(amount) }}</div>
                <div class="cost-available">
                  拥有: {{ formatNumber(getResourceAmount(resource)) }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 维护成本 -->
        <div class="info-section" v-if="building?.maintenance">
          <h3>维护成本</h3>
          <div class="maintenance-grid">
            <div 
              v-for="(amount, resource) in building.maintenance" 
              :key="resource"
              class="maintenance-card"
            >
              <div class="maintenance-icon">{{ getResourceIcon(resource) }}</div>
              <div class="maintenance-details">
                <div class="maintenance-name">{{ getResourceName(resource) }}</div>
                <div class="maintenance-amount">{{ formatNumber(amount) }}/秒</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 建造时间 -->
        <div class="info-section" v-if="building?.buildTime">
          <h3>建造时间</h3>
          <div class="time-info">
            <div class="time-icon">⏱️</div>
            <div class="time-text">{{ formatTime(building.buildTime) }}</div>
          </div>
        </div>

        <!-- 前置条件 -->
        <div class="info-section" v-if="building?.requirements?.length">
          <h3>前置条件</h3>
          <div class="requirements-list">
            <div 
              v-for="requirement in building.requirements" 
              :key="requirement.type"
              class="requirement-item"
              :class="{ met: isRequirementMet(requirement) }"
            >
              <div class="requirement-icon">
                {{ isRequirementMet(requirement) ? '✅' : '❌' }}
              </div>
              <div class="requirement-text">
                {{ formatRequirement(requirement) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 升级信息 -->
        <div class="info-section" v-if="building?.upgrades">
          <h3>升级效果</h3>
          <div class="upgrade-info">
            <div class="upgrade-levels">
              <div 
                v-for="level in 5" 
                :key="level"
                class="level-item"
              >
                <div class="level-number">Lv.{{ level }}</div>
                <div class="level-effects">
                  <div 
                    v-for="effect in building.effects" 
                    :key="effect.type"
                    class="level-effect"
                  >
                    {{ getEffectName(effect.type) }}: 
                    +{{ formatNumber(effect.value * level) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 建筑统计 -->
        <div class="info-section">
          <h3>建筑统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-label">建筑类型</div>
              <div class="stat-value">{{ getCategoryName(building?.category) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">解锁等级</div>
              <div class="stat-value">{{ building?.unlockLevel || 1 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">最大等级</div>
              <div class="stat-value">{{ building?.maxLevel || 10 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">建筑规模</div>
              <div class="stat-value">{{ building?.size || '1x1' }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn secondary" @click="$emit('close')">
          关闭
        </button>
        <button 
          class="btn primary"
          :disabled="!canBuild"
          @click="handleBuild"
        >
          {{ canBuild ? '建造' : '无法建造' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useResourcesStore, useTechnologyStore } from '@/stores'

interface BuildingEffect {
  type: string
  value: number
}

interface BuildingRequirement {
  type: string
  id: string
  level?: number
}

interface Building {
  id: string
  name: string
  description: string
  category: string
  icon?: string
  cost?: Record<string, number>
  maintenance?: Record<string, number>
  buildTime?: number
  effects?: BuildingEffect[]
  requirements?: BuildingRequirement[]
  upgrades?: boolean
  unlockLevel?: number
  maxLevel?: number
  size?: string
}

interface Props {
  building: Building | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
  build: [building: Building]
}>()

const resourcesStore = useResourcesStore()
const technologyStore = useTechnologyStore()

// 计算属性
const canBuild = computed(() => {
  if (!props.building?.cost) return true
  
  return Object.entries(props.building.cost).every(([resource, amount]) => {
    return resourcesStore.resources[resource] >= (amount as number)
  })
})

// 方法
function getCategoryName(category?: string): string {
  const categories: Record<string, string> = {
    infrastructure: '基础设施',
    industrial: '工业建筑',
    research: '研究设施',
    military: '军事建筑',
    commercial: '商业建筑'
  }
  return categories[category || ''] || category || '未知'
}

function getEffectIcon(type: string): string {
  const icons: Record<string, string> = {
    energy_production: '⚡',
    metal_production: '⛏️',
    crystal_production: '💎',
    research_production: '🔬',
    credits_production: '💰',
    population_capacity: '👥',
    defense: '🛡️',
    ship_production: '🚀',
    storage_capacity: '📦'
  }
  return icons[type] || '📈'
}

function getEffectName(type: string): string {
  const names: Record<string, string> = {
    energy_production: '能源产量',
    metal_production: '金属产量',
    crystal_production: '水晶产量',
    research_production: '研究产量',
    credits_production: '信用点产量',
    population_capacity: '人口容量',
    defense: '防御力',
    ship_production: '舰船生产速度',
    storage_capacity: '存储容量'
  }
  return names[type] || type
}

function getResourceIcon(resource: string): string {
  const icons: Record<string, string> = {
    energy: '⚡',
    metals: '⛏️',
    crystals: '💎',
    credits: '💰',
    research: '🔬',
    influence: '🎭'
  }
  return icons[resource] || '❓'
}

function getResourceName(resource: string): string {
  const names: Record<string, string> = {
    energy: '能源',
    metals: '金属',
    crystals: '水晶',
    credits: '信用点',
    research: '研究点',
    influence: '影响力'
  }
  return names[resource] || resource
}

function formatEffectValue(effect: BuildingEffect): string {
  const value = effect.value > 0 ? `+${effect.value}` : effect.value.toString()
  return `${value}/秒`
}

function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

function formatTime(seconds: number): string {
  if (seconds < 60) return `${seconds}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
  return `${Math.floor(seconds / 86400)}天`
}

function hasEnoughResource(resource: string, amount: number): boolean {
  return resourcesStore.resources[resource] >= amount
}

function getResourceAmount(resource: string): number {
  return resourcesStore.resources[resource] || 0
}

function isRequirementMet(requirement: BuildingRequirement): boolean {
  switch (requirement.type) {
    case 'technology':
      return technologyStore.isResearched(requirement.id)
    case 'building':
      // 检查是否有指定建筑
      return true // 简化实现
    default:
      return true
  }
}

function formatRequirement(requirement: BuildingRequirement): string {
  switch (requirement.type) {
    case 'technology':
      return `需要科技: ${requirement.id}`
    case 'building':
      return `需要建筑: ${requirement.id} (等级 ${requirement.level || 1})`
    default:
      return `${requirement.type}: ${requirement.id}`
  }
}

function handleBuild() {
  if (props.building && canBuild.value) {
    emit('build', props.building)
    emit('close')
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

.modal-content {
  background: linear-gradient(135deg, #1a1a2e, #16213e);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 16px;
  max-width: 800px;
  width: 100%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 212, 255, 0.2);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.3);
}

.header-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.building-icon {
  font-size: 3rem;
}

.building-title h2 {
  margin: 0 0 0.25rem 0;
  color: #ffffff;
  font-size: 1.5rem;
}

.building-category {
  color: #00d4ff;
  font-size: 0.875rem;
  font-weight: 500;
}

.close-btn {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 8px;
  padding: 0.5rem;
  color: #cccccc;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 1.2rem;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
}

.info-section {
  margin-bottom: 2rem;
}

.info-section h3 {
  color: #00d4ff;
  font-size: 1.1rem;
  margin: 0 0 1rem 0;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid rgba(0, 212, 255, 0.3);
}

.description {
  color: #cccccc;
  line-height: 1.6;
  margin: 0;
}

.effects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

.effect-card {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background: rgba(0, 255, 136, 0.1);
  border: 1px solid rgba(0, 255, 136, 0.3);
  border-radius: 8px;
}

.effect-icon {
  font-size: 1.5rem;
  min-width: 30px;
}

.effect-details {
  flex: 1;
}

.effect-name {
  color: #00ff88;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.effect-value {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
}

.cost-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.cost-card {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background: rgba(245, 158, 11, 0.1);
  border: 1px solid rgba(245, 158, 11, 0.3);
  border-radius: 8px;
}

.cost-card.insufficient {
  background: rgba(255, 68, 68, 0.1);
  border-color: rgba(255, 68, 68, 0.3);
}

.cost-icon {
  font-size: 1.5rem;
  min-width: 30px;
}

.cost-details {
  flex: 1;
}

.cost-name {
  color: #f59e0b;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.cost-card.insufficient .cost-name {
  color: #ff4444;
}

.cost-amount {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.cost-available {
  color: #888888;
  font-size: 0.875rem;
}

.maintenance-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.maintenance-card {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background: rgba(255, 107, 107, 0.1);
  border: 1px solid rgba(255, 107, 107, 0.3);
  border-radius: 8px;
}

.maintenance-icon {
  font-size: 1.5rem;
  min-width: 30px;
}

.maintenance-details {
  flex: 1;
}

.maintenance-name {
  color: #ff6b6b;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.maintenance-amount {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.time-icon {
  font-size: 1.5rem;
}

.time-text {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 500;
}

.requirements-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.requirement-item.met {
  background: rgba(0, 255, 136, 0.1);
}

.requirement-icon {
  font-size: 1.2rem;
}

.requirement-text {
  color: #cccccc;
  flex: 1;
}

.requirement-item.met .requirement-text {
  color: #00ff88;
}

.upgrade-levels {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
}

.level-item {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.level-number {
  color: #00d4ff;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.level-effects {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.level-effect {
  color: #cccccc;
  font-size: 0.875rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
}

.stat-item {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  text-align: center;
}

.stat-label {
  color: #888888;
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}

.stat-value {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.3);
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
}

.btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
}

.btn.primary {
  background: linear-gradient(135deg, #00d4ff, #0099cc);
  color: #000000;
}

.btn.primary:hover:not(:disabled) {
  background: linear-gradient(135deg, #0099cc, #007399);
  transform: translateY(-1px);
}

.btn:disabled {
  background: rgba(128, 128, 128, 0.3);
  color: #888888;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    margin: 0.5rem;
    max-height: 95vh;
  }
  
  .modal-header {
    padding: 1rem;
  }
  
  .header-info {
    gap: 0.75rem;
  }
  
  .building-icon {
    font-size: 2rem;
  }
  
  .building-title h2 {
    font-size: 1.25rem;
  }
  
  .modal-body {
    padding: 1rem;
  }
  
  .effects-grid,
  .cost-grid,
  .maintenance-grid {
    grid-template-columns: 1fr;
  }
  
  .upgrade-levels,
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
  
  .modal-footer {
    padding: 1rem;
    flex-direction: column;
  }
}
</style>